import {
  CanActivate,
  ExecutionContext,
  Injectable,
  Logger,
  UnauthorizedException,
} from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { IS_PUBLIC_KEY } from './auth.decorator';
import { Reflector } from '@nestjs/core';
import { RedisService } from '../redis/redis.service';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(
    private jwtService: JwtService,
    private reflector: Reflector,
    private readonly redisService: RedisService, // 用于从 Redis 获取用户信息
  ) {}

  private readonly logger = new Logger(AuthGuard.name);

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const request = context.switchToHttp().getRequest();

    const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);
    if (isPublic) {
      // 💡 See this condition
      return true;
    }
    const token = request.headers['access_token'];
    this.logger.log(`token:${token}`);

    if (!token) {
      throw new UnauthorizedException();
    }
    try {
      const payload = await this.jwtService.verifyAsync(token, {
        secret: 'zjj',
      });
      const userId = payload.sub;

      // 从 Redis 或数据库获取用户详细信息
      // 将用户信息存储到请求对象中
      request.user = await this.redisService.get(`userInfo${userId}`); // 这里可以存储更丰富的用户信息
      return true;
    } catch (e) {
      this.logger.error(e);
      throw new UnauthorizedException();
    }
  }
}
